package cn.wuyi.common.context;


import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.wuyi.common.base.Tenant;
import cn.wuyi.common.rest.ResponseResult;
import cn.wuyi.common.rest.RestUtils;
import cn.wuyi.common.rest.Result;
import cn.wuyi.common.rest.ResultUtil;
import cn.wuyi.common.util.JacksonUtil;


public class ContextUtil {
	
	private static Logger log = LoggerFactory.getLogger(ContextUtil.class);
	

	private static final String TENANT_SERVICE_URI_PROPERTY = "service.tenantUri";
	public static final java.lang.String COMMON_DOMAIN = "common";
	
	private static String getTenantUrl(String methodName){
		String tenantUri = System.getProperty(TENANT_SERVICE_URI_PROPERTY);
		if(StringUtils.isEmpty(tenantUri)){
			log.error("env.properties:System property ["+TENANT_SERVICE_URI_PROPERTY +"] is null");
			return null;
		}
		if(!tenantUri.endsWith("/")){
			tenantUri += "/";
		}
		if(methodName != null && methodName.startsWith("/")){
			methodName = methodName.substring(1);
		}
		tenantUri += methodName;
		log.debug("访问租户服务的url is {}",tenantUri);
		return tenantUri;
	} 
	 
	public static Tenant getTenantByDomain(String domain,String type){
		String tenantUrl = getTenantUrl("gettbydomain");
		if(tenantUrl==null){
			Tenant t = new Tenant();
			t.setId("-1");
			return t;
		}
		tenantUrl += "?domain="+domain+"&type="+type;
		if(StringUtils.isBlank(type)){
			type=COMMON_DOMAIN;
		}
		ResponseResult<String> response = RestUtils.getRequest(tenantUrl, null, null);
		String json = response.getBody();
		Result<Tenant> result = ResultUtil.buildResult(json, Tenant.class);
		if(result != null && "200".equals(result.getStatus())){
			log.debug("根据域名domain is {} 获取的租户信息Tenant value is {}",domain,JacksonUtil.defaultMapper().toJson(result.getData()));
			return result.getData();
		}else{
			return null;
		}
	}
	
	public static  Tenant getTenantById(String tenantId){
		if(tenantId == null){
			log.warn("根据租户Id获取租户服务的的参数tenantId is null");
			return null;
		}
		String tenantUrl = getTenantUrl("getTenantById");
		tenantUrl += "?id="+tenantId;
		ResponseResult<String> response = RestUtils.getRequest(tenantUrl, null, null);
		String json = response.getBody();
		Result<Tenant> result = ResultUtil.buildResult(json, Tenant.class);
		if(result != null && "200".equals(result.getStatus())){
			log.debug("根据租户tenantId is {} 获取的租户信息Tenant value is {}",tenantId,JacksonUtil.defaultMapper().toJson(result.getData()));
			return result.getData();
		}else{
			return null;
		}
	}
	
	
	public static String getDynDbSwitchTag(String tenantId){
		Tenant tenant = getTenant(tenantId);
		if(tenant == null){
			log.info("### Tenant is null, tenantId is {} !",tenantId);
			return "false";
		}
		String unitType = tenant.getUnittype();
		
		if(ContextParameter.DYNAMIC_UNIT_TYPE_VALUE.equals(unitType)){
			log.debug("### UnitType is {} !",unitType);
			return "true";
		}else{
			return "false";
		}
		
	}
	
	public static String getDynDbPrefix(String tenantId){
		Tenant tenant = getTenant(tenantId);
		if(tenant == null){
			log.info("### Tenant is null, tenantId is {} !",tenantId);
			return null;
		}
		String unitType = tenant.getUnittype();
		if(ContextParameter.DYNAMIC_UNIT_TYPE_VALUE.equals(unitType)){
			String tempLateCode = tenant.getTemplateCode();
			log.debug("### UnitType is {} , templateCode : {} !",unitType,tempLateCode);
			return StringUtils.isEmpty(tempLateCode) ? tempLateCode : tempLateCode.toLowerCase();
		}else{
			return null;
		}
		
	}
	
	public static String getDynDbClusterTag(String tenantId){
		return "0";
	}
	
	private static Tenant getTenant(String tenantId){
		if(tenantId == null){
			tenantId = ContextHolder.getContext().getTenantId();
		}
		Tenant tenant = ContextHolder.getContext().getTenant();
		if(tenant == null){
			if(tenantId != null){
				tenant = getTenantById(tenantId);
			}
		}
		return tenant;
	}
	
	public static void applyDynamicParameter(String tenantId){
		String switchTag = ContextUtil.getDynDbSwitchTag( tenantId);
		String dbPrefix = ContextUtil.getDynDbPrefix( tenantId);
		String clusterTag = ContextUtil.getDynDbClusterTag( tenantId);
		log.debug("### current switchTag is {} , dbPrefix is {} , clusterTag is {} !",switchTag,dbPrefix,clusterTag);
		ContextHolder.getContext().add(ContextParameter.DYNAMIC_DB_SWITCH_TAG,switchTag);
		ContextHolder.getContext().add(ContextParameter.DYNAMIC_DB_PREFIX_PROPERTY, dbPrefix);
		ContextHolder.getContext().add(ContextParameter.DYNAMIC_DB_CLUSTER_NUMBER_PROPERTY, clusterTag);
	}
	
	
}
